package com.quanquan.store.dao;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;

@Repository
public class OrderCacheDao {

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	private static final String PREFIX = "couponOrder-";

	/**
	 * 获取缓存中的订单
	 * 
	 * @param orderNum
	 * @return
	 */
	public String get(@NotNull String orderNum) {
		if (stringRedisTemplate.hasKey(PREFIX.concat(orderNum))) {
			return orderNum;
//			return stringRedisTemplate.opsForValue().get(PREFIX.concat(orderNum));
		} else {
			return null;
		}
	}

	/**
	 * 向缓存中保存订单
	 * 
	 * @param orderNum
	 * @return
	 */
	public boolean save(@NotNull String orderNum) {
		if (orderNum == null) {
			return false;
		} else {
			// 设置订单4分钟过期
			stringRedisTemplate.opsForValue().set(PREFIX.concat(orderNum),
					orderNum, 5, TimeUnit.MINUTES);
			return true;
		}
	}

	/**
	 * 删除缓存
	 * 
	 * @param orderNum
	 * @return
	 */
	public boolean delete(@NotNull String orderNum) {
		if (stringRedisTemplate.hasKey(PREFIX.concat(orderNum))) {
			stringRedisTemplate.delete(PREFIX.concat(orderNum));
			return true;
		} else {
			return false;
		}
	}
}
